import _ from 'underscore';
import moment from 'moment';

import { Scope } from 'lib/scopeFactory';
import { Warning } from 'lib/components/Notify.jsx';

import { request2 } from '../../apis/core-util';
import { relativeDays, getDayFromAlias } from '../../common/DateRangeStoreEnhanced.es6';

export default class FavoriteScope extends Scope {
  constructor(props) {
    super(props);

    this.$state = {
      name: props.title,
      nameError: null,
      isProcessing: false,
      selectedItem: {
        isCustom: false
      }
    }; // $state

    _.extend(this.$state.selectedItem, this.getSelectedItem(props));
  } // constructor

  $receive(nextProps) {
    _.extend(this.$state.selectedItem, this.getSelectedItem(nextProps));
  } // $receive

  getSelectedItem(props) {
    let result = {
      isNatural: false,
      item: relativeDays[0]
    };

    if (props.alias) {
      let time = getDayFromAlias(props.alias);
      if (time) {
        result.isNatural = time.isNatural;
        result.item = time.item;
      }
    }

    return result;
  } // getSelectedItem

  $change_name({ name }) {
    this.$state.name = name;
    if (name) {
      this.$state.nameError = '';
    } else {
      this.$state.nameError = '收藏的名称不能为空';
    }

    this.emit();
  } // $change_name

  $change_time({ item }) {
    this.$state.selectedItem = item;

    this.emit();
  } // $change_time

  $add_bookmark() {
    if (this.processingHandler || !this.$state.name) {
      return;
    }

    this.postBookmark('',
      error => Warning('收藏添加失败！'),
      (data, name) => this.viewInstance.close({
        isSuccess: true,
        result: {
          $type: 'added_favorite',
          data: _.extend(data, {
            name: name,
            alias: this.$state.selectedItem.item.alias
          })
        }
      })
    );
  } // $save_bookmark

  $update_bookmark({ id }) {
    if (this.processingHandler || !this.$state.name) {
      return;
    }

    this.postBookmark(`/${ id }`,
      error => Warning('收藏更新失败！'),
      (data, name) => this.viewInstance.close({
        isSuccess: true,
        result: {
          $type: 'updated_favorite',
          data: {
            id: id,
            name: name,
            contentType: '/segmentation/',
            alias: this.$state.selectedItem.item.alias
          }
        }
      })
    );
  } // $update_bookmark

  $remove_bookmark({ id }) {
    if (this.processingHandler) {
      return;
    }

    this.processingHandler = request2({
      url: `sd/${ BlueWare.appId }/api/bookmarks/bookmark/${ id }`,
      method: 'delete'
    })
    .progress(() => {
      this.$state.isProcessing = true;

      this.update();
    })
    .fail(error => Warning('收藏删除失败！'))
    .done(() => this.viewInstance.close({
      isSuccess: true,
      result: {
        $type: 'removed_favorite',
        data: {
          contentType: '/segmentation/',
          id
        }
      }
    }))
    .always(() => {
      this.$state.isProcessing = false;
      this.processingHandler = null;

      this.emit();
    });
  } // $remove_bookmark

  postBookmark(id, failCallback, doneCallback) {
    let props = this.viewInstance.props;
    let body = {
      dashboards: [],
      data: (typeof props.chartParameter === 'string') ? props.chartParameter : JSON.stringify(props.chartParameter),
      name: this.$state.name,
      related_events: props.events,
      time: this.$state.selectedItem.item.alias,
      type: '/segmentation/'
    };

    this.processingHandler = request2({
      url: `sd/${ BlueWare.appId }/api/bookmarks/bookmark${ id }`,
      method: 'post',
      body
    })
    .progress(() => {
      this.$state.isProcessing = true;

      this.update();
    })
    .fail(failCallback)
    .done(data => doneCallback(data, body.name))
    .always(() => {
      this.$state.isProcessing = false;
      this.processingHandler = null;

      this.emit();
    });
  }
}
